package com.aidex.biz.service.impl;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.bo.BusinessSetBo;
import com.aidex.biz.domain.enums.CustomerEnum;
import com.aidex.biz.domain.vo.*;
import com.aidex.biz.mapper.CustomerMapper;
import com.aidex.biz.mapper.TempShareMapper;
import com.aidex.biz.service.*;
import com.aidex.biz.utils.RAESUtils;
import com.aidex.biz.utils.RongXiangKeAESUtil;
import com.aidex.biz.utils.TencentSmsUtils;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.annotation.Log;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.exception.CustomException;
import com.aidex.common.utils.HardwareID;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.http.HttpUtils;
import com.aidex.common.utils.sign.Md5Utils;
import com.aidex.common.utils.sms.ChuangLanSmsClient;
import com.aidex.common.utils.sms.JdSmsClient;
import com.aidex.common.utils.sql.SqlUtil;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.framework.cache.DictUtils;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.system.domain.SysDictData;
import com.aidex.system.mapper.SysUserMapper;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.ISysUserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.api.client.json.Json;
import com.jdcloud.sdk.service.sms.model.BatchSendResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.logging.Level;

/**
 * 左心房客户推送信息Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-04-03
 */
@Service
@Transactional(readOnly = true)
public class CustomerServiceImpl extends BaseServiceImpl<CustomerMapper, Customer> implements CustomerService {
    private static final Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class);
    final String secretKey = "11662107190";

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TempShareService tempShareService;

    @Autowired
    private TempShareMapper tempShareMapper;
    @Autowired
    private ShareLogService shareLogService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private AccountLogService accountLogService;
    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private CustomerXiezuService customerXiezuService;
    @Autowired
    private XiezuService xiezuService;
    @Autowired
    private PushCustomerService pushCustomerService;

    @Autowired
    private CheYouRongOrderService cheYouRongOrderService;

    /**
     * 获取单条数据
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    public Customer get(Customer customer) {
        Customer dto = super.get(customer);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 左心房客户推送信息id
     * @return 左心房客户推送信息
     */
    @Override
    public Customer get(String id) {
        Customer dto = super.get(id);
        return dto;
    }


    /**
     * 查询左心房客户推送信息列表
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<Customer> findList(Customer customer) {
        return super.findList(customer);
    }

    /**
     * 分页查询左心房客户推送信息列表
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findPage(Customer customer) {
        return super.findPage(customer);
    }

    /**
     * 保存左心房客户推送信息
     *
     * @param customer
     * @return 结果
     */
    @Override
    public boolean save(Customer customer) {
        return super.save(customer);
    }


    /**
     * 删除左心房客户推送信息信息
     *
     * @param customer
     * @return 结果
     */
    @Override
    public boolean remove(Customer customer) {
        return super.remove(customer);
    }

    /**
     * 批量删除左心房客户推送信息
     *
     * @param ids 需要删除的左心房客户推送信息ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteCustomerByIds(String[] ids) {
        return mapper.deleteCustomerByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param customer 左心房客户推送信息
     * @return 结果
     */
    @Override
    public int findMaxSort(Customer customer) {
        return NumberUtils.nextOrder(mapper.findMaxSort(customer));
    }

    @Override
    public Customer findCustomerByphone(String phone) {
        Customer customer = new Customer();
        customer.setPhone(phone);
        List<Customer> customers= mapper.findList(customer);
        return customers.size()>0?customers.get(0):null;
    }
    @Override
    public boolean findCustomerByphone(Customer customer) {
        boolean isJiangxi = false;
        String[] citys={"南昌市","赣州市","九江市","宜春市","上饶市","吉安市","抚州市","新余市","萍乡市","景德镇","鹰潭市"};
        for(String city:citys){
            if(StringUtils.isNotEmpty(customer.getCityName())&&city.contains(customer.getCityName())){
                isJiangxi=true;
                break;
            }
        }
        if(isJiangxi){
            JSONObject res=cheYouRongOrderService.checkOrder(customer);
            return !res.getBoolean("data");
        }else{
            return mapper.findList(customer).size() > 0;
        }

    }

    @Transactional(readOnly = false)
    @Override
    public Map savePushCustomer(Customer customer) {
        // 先看数据是不是江西的
        boolean isJiangxi = false;
        Map maps = new HashMap();
        String[] citys={"南昌市","赣州市","九江市","宜春市","上饶市","吉安市","抚州市","新余市","萍乡市","景德镇","鹰潭市"};
        for(String city:citys){
            if(city.contains(customer.getCityName())){
                isJiangxi=true;
                break;
            }
        }
        if(isJiangxi&&StringUtils.isNotEmpty(customer.getCityName())){
            // 推送
            JSONObject res=cheYouRongOrderService.insertOrder(customer);
            PushCustomer pushCustomer=new PushCustomer();
            pushCustomer.setIsNewRecord();
            pushCustomer.setCusName(customer.getCusName());
            pushCustomer.setPhone(customer.getPhone());
            pushCustomer.setIsRep(0);
            pushCustomer.setLaiyuan(customer.getLaiyuan());
            pushCustomer.setCityName(customer.getCityName());
            if("200".equals(res.getString("code"))){
                pushCustomer.setRemark("江西推送成功");
                maps.put("code", "200");
                maps.put("message", "推送成功");
            }else{
                pushCustomer.setRemark("江西推送失败成功");
                maps.put("code", "500");
                maps.put("message", "推送失败");
            }
            pushCustomerService.save(pushCustomer);

        }else{
            try {
                // 保存客户
                Date date=new Date();
                String pushId=UUID.randomUUID().toString();
                customer.setId(UUID.randomUUID().toString());
                customer.setIsNewRecord();
                customer.setReceiveTime(date);
                customer.setCreateTime(date);
                customer.setLastTime(date);
                customer.setIsDail(0l);
                customer.setType("1");
                customer.setLaiyuanType("1");// 广告客户
                customer.setStatus(CustomerEnum.DAI_FP.getStatus());
                customer.setUserId(null);
                customer.setUserName(null);
                customer.setDeptId(null);
                customer.setDeptName(null);
                customer.setIsRep(0);
                customer.setPushId(pushId);
                maps.put("code", "200");
                maps.put("message", "推送成功");
                this.save(customer);


                // 保存分配
                PushCustomer pushCustomer=new PushCustomer();
                pushCustomer.setId(pushId);
                pushCustomer.setIsNewRecord();
                pushCustomer.setCusName(customer.getCusName());
                pushCustomer.setPhone(customer.getPhone());
                pushCustomer.setIsRep(0);
                pushCustomer.setLaiyuan(customer.getLaiyuan());
                pushCustomer.setCityName(customer.getCityName());
                pushCustomer.setRemark(maps.get("message").toString());
                pushCustomer.setCreateTime(date);
                pushCustomerService.save(pushCustomer);
                // 保存动态
                CustomerDongtai customerDongtai=new CustomerDongtai();
                customerDongtai.setCustomerId(customer.getId());
                customerDongtai.setType("1");
                customerDongtai.setContent(customer.getLaiyuan()+"-"+"广告客户进线");
                customerDongtaiService.save(customerDongtai);
            } catch (Exception exception) {
                log.error("调用ApiPushCustomerController.savePushCustomer", JSONObject.toJSONString(customer));
                maps.put("code", "500");
                maps.put("message", exception.getMessage());
                maps.put("data", JSONObject.toJSONString(customer));
            }
        }



        return maps;
    }

    /**
     * 分配客户给用户 废弃
     *
     * @param customer
     */
    @Transactional(readOnly = false)
    @Override
    public void shareCustomer(Customer customer) {
        // 根据客户信息查询对应的用户
        // SysUser user = findNextShareUser(customer);
        // 如果有分配的用户
//        if (null != user) {
//            try {
//
//                //开始分配
//                customer = mapper.get(customer.getId());
//                customer.setUserId(user.getUserId());
//                customer.setUserName(user.getName());
//                customer.setDeptId(user.getDeptId());
//                customer.setDeptName(user.getDeptName());
//                customer.setCompanyId(user.getCompanyId());
//                customer.setShareDate(new Date());
//                // 添加临时分配记录
//                TempShare tempShare = new TempShare();
//                tempShare.setSysUserId(user.getId());
//                tempShareService.save(tempShare);
//                // 修改分配次数
//                user.setDayShareCount(user.getDayShareCount() + 1);
//                userService.updateDayShareCount(user);
//                // 分配记录
//                ShareLog shareLog = new ShareLog();
//                shareLog.setCustomerId(customer.getId());
//                shareLogService.save(shareLog);
//
//                customer.setStatus(CustomerEnum.YI_FP.getStatus());
//                customer.setInfo("分配成功！");
//                customer.setOwnType("0");
//            } catch (Exception e) {
//                customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
//                customer.setInfo(e.getMessage());
//            }
//
//        } else {
//            customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
//            customer.setInfo("没找到分配用户！");
//            mapper.update(customer);
//        }
//        if (mapper.update(customer) > 0 && "-1".equals(customer.getStatus())) {
//
//            JSONObject jsonObject =
//                    JSONObject.parseObject(TencentSmsUtils.SmsSend(TencentSmsUtils.templateId_1,
//                            customer.getCusName(),user.getPhonenumber()));
//            SmsLog smsLog = new SmsLog();
//            smsLog.setPhone(user.getPhonenumber());
//            smsLog.setName(customer.getCusName());
//            smsLog.setCompanyId(user.getCompanyId());
//            smsLog.setUserId(user.getPhonenumber());
//            smsLog.setUserName(user.getName());
//            JSONArray jsonArray=jsonObject.getJSONArray("SendStatusSet");
//            for(int i=0;i<jsonArray.size();i++){
//                smsLog.setStatus(jsonArray.getJSONObject(i).getString("Code"));
//                smsLog.setRemark(jsonArray.getJSONObject(i).getString("Message"));
//                smsLogService.save(smsLog);
//            }
//
//        }

    }

    /**
     * 分配客户给用户
     *
     * @param customer
     */
    @Override
    @Transactional(readOnly = false)
    public int shareCustomer(Customer customer, SysUser user,Boolean isSms) {
        int result = 0;
        if (null != user) {
            try {
                //开始分配
                customer = mapper.get(customer.getId());
                // 如果是不是重复客户
                if(true){
                    customer.setUserId(user.getUserId());
                    customer.setUserName(user.getName());
                    customer.setDeptId(user.getDeptId());
                    customer.setDeptName(user.getDeptName());
                    customer.setCompanyId(user.getCompanyId());
                    customer.setShareDate(new Date());
                    // 添加临时分配记录
                    TempShare tempShare = new TempShare();
                    tempShare.setSysUserId(user.getId());
                    tempShare.setCustomerId(customer.getId());
                    tempShareService.save(tempShare);
                    // 修改分配次数
                    user.setDayShareCount(user.getDayShareCount() + 1);
                    userService.updateDayShareCount(user);
                    // 分配记录
                    ShareLog shareLog = new ShareLog();
                    shareLog.setCustomerId(customer.getId());
                    shareLog.setUserId(user.getUserId());
                    shareLog.setUserName(user.getName());
                    shareLog.setDeptId(user.getDeptId());
                    shareLog.setDeptName(user.getDeptName());
                    shareLog.setCompanyId(customer.getCusName());
                    shareLogService.save(shareLog);
                    customer.setStatus(CustomerEnum.MY_CUS.getStatus());
                    customer.setOwnType("0");
                    // 分配时间
                    customer.setReceiveTime(new Date());
                    // 如果是成交客户
                    if(1==customer.getIsCj()){
                        customer.setIsCj(0);
                        customer.setProgress("gjz");
                    }
                    if (mapper.update(customer) > 0 && CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())&&isSms) {
                        String params=
                                user.getPhonenumber()+","+customer.getCusName();
                        JSONObject jsonObject =
                                ChuangLanSmsClient.sendSms(params);
                        SmsLog smsLog = new SmsLog();
                        smsLog.setPhone(user.getPhonenumber());
                        smsLog.setName(customer.getCusName());
                        smsLog.setCompanyId(user.getCompanyId());
                        smsLog.setUserId(user.getPhonenumber());
                        smsLog.setUserName(user.getName());
                        smsLog.setStatus(jsonObject.getString("code"));
                        smsLog.setRemark(jsonObject.getString("errorMsg"));
                        smsLogService.save(smsLog);

                        CustomerDongtai customerDongtai=new CustomerDongtai();
                        customerDongtai.setCustomerId(customer.getId());
                        customerDongtai.setType("1");
                        customerDongtai.setContent("系统分配给-"+user.getName());
                        customerDongtaiService.save(customerDongtai);
                        JSONObject jsonObjectSocket=new JSONObject();
                        jsonObjectSocket.put("type","fenpeiNewCus");
                        jsonObjectSocket.put("msg","您有新的客户进线-"+customer.getCusName());
                        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,user.getId(),jsonObjectSocket.toJSONString()
                                );
                    }
                }else{
                    // 重复客户 添加协助信息
                    // 添加协助员工信息
                    CustomerXiezu customerXiezu=new CustomerXiezu();
                    String[] users={user.getUserId()};
                    String[] usernames={user.getName()};
                    customerXiezu.setXiezuUsers(users);
                    customerXiezu.setXiezuUserNames(usernames);
                    customerXiezu.setCustomerId(customer.getId());
                    customerXiezu.setUserName("系统分配");
                    for(String userid:customerXiezu.getXiezuUsers()){
                        customerXiezu.setId(Md5Utils.hash(userid+customerXiezu.getCustomerId()));
                        customerXiezu.setXiezuUserId(userid);
                        if(null==customerXiezuService.get(Md5Utils.hash(userid+customerXiezu.getCustomerId()))){
                            try{
                                customerXiezu.setIsNewRecord();
                                customerXiezuService.save(customerXiezu);
                            }catch (Exception e){
                                log.info("协助人员添加失败"+e.getMessage());
                            }
                        }else{
                            customerXiezu.setCreateTime(new Date());
                            customerXiezuService.save(customerXiezu);
                        }
                    }
                    // 拼接数据
                    String userids="",userNames="";
                    for(int i=0;i< customerXiezu.getXiezuUsers().length;i++){
                        if(i==customerXiezu.getXiezuUsers().length-1){
                            userids+=customerXiezu.getXiezuUsers()[i];
                            userNames+=customerXiezu.getXiezuUserNames()[i];
                        }else {
                            userids+=customerXiezu.getXiezuUsers()[i]+",";
                            userNames+=customerXiezu.getXiezuUserNames()[i]+",";
                        }
                    }
                    // 客户动态分配
                    if(isSms){
                        CustomerDongtai customerDongtai=new CustomerDongtai();
                        customerDongtai.setCustomerId(customerXiezu.getCustomerId());
                        customerDongtai.setType("2");
                        customerDongtai.setContent("自动分配协助(重复客户)-"+user.getName());
                        customerDongtaiService.save(customerDongtai);
                    }

                    // 协助记录
                    Xiezu xiezu=new Xiezu();
                    xiezu.setXiezuUserIds(userids);
                    xiezu.setXiezuUserNames(userNames);
                    xiezu.setCustomerId(customerXiezu.getCustomerId());
                    xiezu.setUserName("系统分配");
                    xiezuService.save(xiezu);

                    // 添加临时分配记录
                    TempShare tempShare = new TempShare();
                    tempShare.setSysUserId(user.getId());
                    tempShareService.save(tempShare);
                    // 修改分配次数
                    user.setDayShareCount(user.getDayShareCount() + 1);
                    userService.updateDayShareCount(user);
                    // 分配记录
                    ShareLog shareLog = new ShareLog();
                    shareLog.setCustomerId(customer.getId());
                    shareLog.setUserId(user.getUserId());
                    shareLog.setUserName(user.getName());
                    shareLog.setDeptId(user.getDeptId());
                    shareLog.setDeptName(user.getDeptName());
                    shareLog.setCompanyId(customer.getCusName());
                    shareLogService.save(shareLog);
                    customer.setStatus(CustomerEnum.MY_CUS.getStatus());
                    customer.setShareDate(new Date());
                    if (mapper.update(customer) > 0 && CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())&&isSms) {
                        // 发送协助短信
                        JSONObject jsonObject =
                                JSONObject.parseObject(TencentSmsUtils.SmsSend(TencentSmsUtils.templateId_2,
                                customer.getCusName(),user.getPhonenumber()));
                        SmsLog smsLog = new SmsLog();
                        smsLog.setPhone(user.getPhonenumber());
                        smsLog.setName(customer.getCusName());
                        smsLog.setCompanyId(user.getCompanyId());
                        smsLog.setUserId(user.getPhonenumber());
                        smsLog.setUserName(user.getName());
                        JSONArray jsonArray=jsonObject.getJSONArray("SendStatusSet");
                        for(int i=0;i<jsonArray.size();i++){
                            smsLog.setStatus(jsonArray.getJSONObject(i).getString("Code"));
                            smsLog.setRemark(jsonArray.getJSONObject(i).getString("Message"));
                            smsLogService.save(smsLog);
                        }
                    }
                    JSONObject jsonObjectSocket=new JSONObject();
                    jsonObjectSocket.put("type","xiezuCus");
                    jsonObjectSocket.put("msg","您有新的协助客户进线-"+customer.getCusName());
                    WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,user.getId(), jsonObjectSocket.toJSONString());
                }
                PushCustomer pushCustomer=pushCustomerService.get(customer.getPushId());
                if(null!=pushCustomer){
                    // 修改推送的数据
                    pushCustomer.setUserId(user.getUserId());
                    pushCustomer.setUserName(user.getName());
                    pushCustomer.setDeptId(user.getDeptId());
                    pushCustomer.setDeptName(user.getDeptName());
                    pushCustomer.setCompanyId(user.getCompanyId());
                    pushCustomerService.save(pushCustomer);
                }
            } catch (Exception e) {
                customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
                customer.setInfo(e.getMessage());
                mapper.update(customer);
            }

        } else {
            try{
                customer.setStatus(CustomerEnum.FP_SHIBAI.getStatus());
                customer.setInfo("没找到分配用户！");
                mapper.update(customer);
            }catch (Exception e){
                log.error("没找到分配用户错误"+e.getMessage());
            }

        }
        result=1;
        return result;
    }

    @Override
    @Transactional(readOnly = false)
    public int myShareCustomer(Customer customer, SysUser sysUser, Boolean isSms) {
        customer.setUserId(sysUser.getUserId());
        customer.setUserName(sysUser.getName());
        customer.setDeptId(sysUser.getDeptId());
        customer.setDeptName(sysUser.getDeptName());
        customer.setCompanyId(sysUser.getCompanyId());
        customer.setShareDate(new Date());
        customer.setStatus(CustomerEnum.MY_CUS.getStatus());
        customer.setOwnType("0");

        return mapper.update(customer);
    }

    /**
     * 根据客户查询可分配的用户
     *
     * @param customer
     * @return
     */
    @Override
    public SysUser findNextShareUser(Customer customer) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isEmpty(customer.getCityName())) {
            return null;
        }
        String[] areas = customer.getCityName().split("-");
        String area = "";
        if (areas.length == 2) {
            area = areas[1];
        } else {
            area = customer.getCityName();
        }
        params.put("cityName", area);
        params.put("laiyuan", customer.getLaiyuan());
        List<SysUser> sysUserList = iSysUserService.findShareUser(params);
        if (null == sysUserList || sysUserList.size() == 0) {
            //没有可分配的用户了  表示一轮已经分完了
            SysUser sysUser = new SysUser();
            sysUser.setCity(area);
            sysUser.setBusType(customer.getLaiyuan());
            List<SysUser> shareUserList = iSysUserService.findList(sysUser);
            tempShareService.deleteAll(shareUserList);
            //重新查询
            sysUserList = iSysUserService.findShareUser(params);
        }
        //如果查询到用户列表取第一个用户 如果没有用户了，返回空用户
        return sysUserList.size() > 0 ? sysUserList.get(0) : null;
    }

    /**
     * 分配后修改状态
     * 废弃
     *
     * @param customer
     */
    @Transactional(readOnly = false)
    @Override
    public void shareCustomerToSysUser(Customer customer) {
        shareCustomer(customer);
    }

    /**
     * @return 查询一个为分配的用户
     */

    @Override
    public Customer findOne() {
        return mapper.findOne();
    }

    @Transactional(readOnly = false)
    @Override
    public String importData(List<Customer> customers,String status) throws InterruptedException {
        if (StringUtils.isNull(customers) || customers.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int reRep=0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Customer customer : customers) {
            try {
                if(StringUtils.isEmpty(customer.getCusName())){
                    continue;
                }
                customer.setId(UUID.randomUUID().toString());
                if(StringUtils.isEmpty(status)){
                    customer.setStatus(CustomerEnum.DAI_FP.getStatus());
                    customer.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                    customer.setIp(SecurityUtils.getLoginUser().getUser().getLoginIp());
                    customer.setCreateTime(new Date());
                    customer.setLaiyuanType("1");
                    customer.setOwnType("0");
                }else{
                    customer.setStatus(status);
                    customer.setUserId(SecurityUtils.getLoginUser().getUserId());
                    customer.setUserName(SecurityUtils.getLoginUser().getUser().getName());
                    customer.setDeptName(SecurityUtils.getLoginUser().getUser().getDeptName());
                    customer.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
                    customer.setReceiveTime(new Date());
                    customer.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                    customer.setIp(SecurityUtils.getLoginUser().getUser().getLoginIp());
                    customer.setCreateTime(new Date());
                    customer.setLastTime(new Date());
                    customer.setLaiyuanType("1");
                    customer.setOwnType("2");
                }
                if(StringUtils.isEmpty(customer.getFuckCarNoTime())){
                    customer.setFuckCarNoTime(null);
                }

                customer.setType("1");// 车贷
                //判断是否重名
//                Customer res = findCustomerByphone(customer.getPhone());
//                if(null!=res){
//                    reRep++;
//                    continue;
//                }else{
//
//                }

                mapper.insert(customer);
                CustomerDongtai customerDongtai=new CustomerDongtai();
                customerDongtai.setCustomerId(customer.getId());
                customerDongtai.setType("1");
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-导入客户信息");
                customerDongtaiService.save(customerDongtai);
                successNum++;
            } catch (Exception e) {
                failureNum++;
                System.out.println(e.getMessage());
            }
            Thread.sleep(100L);
        }
        if(successNum>0){
            successMsg.append( "操作成功：！成功： " + successNum + " 条，");
        }
        if (failureNum > 0) {
            successMsg.append( "失败：" + failureNum + " 条， ");

        }
        if (reRep > 0) {
            successMsg.append( "重复：" + reRep + " 条");

        }

        return successMsg.toString();
    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateStatus(Customer customer) {
        return mapper.updateStatus(customer);
    }

    @Override
    public Customer findByPhone(Customer customer) {
        return mapper.findByPhone(customer);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findListXieZu(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.findListXieZu(customer));
    }

    @Override
    public PageInfo<Customer> findgonghaiList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.findgonghaiList(customer));
    }

    @Override
    public PageInfo<Customer> findMyList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.findMyList(customer));
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findChengJiaoList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.findChengJiaoList(customer));
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findAllList(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.findAllList(customer));
    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateGongHaiStatus(Customer customer) {
        return mapper.updateGongHaiStatus(customer);
    }

    @Override
    public List<CustomerExpertVo> findAllExportList() {
        return mapper.findAllExportList();
    }

    @Override
    public PageInfo<GuanggaoChengBen> pageGuanggaoChengben(Customer customer) {
        PageDomain page = customer.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.guanggaochengben(customer));
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public HeJiGuanggaoChengBen hejiGuanggaochengben(Customer customer) {
        return mapper.hejiGuanggaochengben(customer);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<GuanggaoChengBen> guanggaoChengben(Customer customer) {
        return mapper.guanggaochengben(customer);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<YuanGongGongziVo> yuangonggongzitongji(Customer customer) {
        return mapper.yuangonggongzitongji(customer);
    }

    @Override
    public PageInfo<Customer> ysfindPage(Customer customer) {
        return super.findPage(customer);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusByJinJianStatus(JinjianInfo jinjianInfo) {
        List<Customer> customers=mapper.selectCustomerIdByJinJianStatus(jinjianInfo);
        Map<String,Object> params=new HashMap<>();
        params.put("list",customers);
        params.put("type",3);
        String content="";
        if("1".equals(jinjianInfo.getIsFk())){
            content="已放款";
        }
        if("1".equals(jinjianInfo.getStatus())){
            content="进件中";
        }
        if("1".equals(jinjianInfo.getJinjianStatus())){
            content="待放款";
        }
        params.put("content","系统操作-"+content+"-更新客户状态为成交客户");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusByJinJianStatus(jinjianInfo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHai48(BusinessSetBo businessSetBo) {
        List<Customer> customers=mapper.selectToHongHai48(businessSetBo);
        Map<String,Object> params=new HashMap<>();
        params.put("list",customers);
        params.put("type",3);
        params.put("content","系统操作-我的客户-"+businessSetBo.getTime()+"（小时）未跟进-更新客户状态为公海客户");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusToHongHai48(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHai15(BusinessSetBo businessSetBo) {
        List<Customer> customers=mapper.selectToHongHai15(businessSetBo);
        Map<String,Object> params=new HashMap<>();
        params.put("list",customers);
        params.put("type",3);
        params.put("content","系统操作-我的客户-"+businessSetBo.getTime()+"（天）未跟进-更新客户状态为公海客户");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusToHongHai15(businessSetBo);

    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHai3(BusinessSetBo businessSetBo) {
        List<Customer> customers=mapper.selectToHongHai3(businessSetBo);
        Map<String,Object> params=new HashMap<>();
        params.put("list",customers);
        params.put("type",3);
        params.put("content","系统操作-我的客户-"+businessSetBo.getTime()+"（天）未跟进-更新客户状态为公海客户");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusToHongHai3(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusToHongHaiXianSuoChi(BusinessSetBo businessSetBo) {
        List<Customer> customers=mapper.selectToHongHaiXianSuoChi(businessSetBo);
        Map<String,Object> params=new HashMap<>();
        params.put("list",customers);
        params.put("type",3);
        params.put("content","系统操作-线索池-"+businessSetBo.getTime()+"（天）未跟进-更新客户状态为公海客户");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusToHongHaiXianSuoChi(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusCancelRep(BusinessSetBo businessSetBo) {
        List<Customer> customers=mapper.selectIsRepToTime(businessSetBo);
        Map<String,Object> params=new HashMap<>();
        params.put("list",customers);
        params.put("type",3);
        params.put("content","系统操作-"+businessSetBo.getTime()+"（天）重复标记-取消重复标记");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusCancelRep(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatusCancelLock(BusinessSetBo businessSetBo) {
        List<Customer> customers=mapper.selectIsLockToTime(businessSetBo);
        Map<String,Object> params=new HashMap<>();
        params.put("list",customers);
        params.put("type",3);
        params.put("content","系统操作-"+businessSetBo.getTime()+"（天）锁定客户-取消锁定");
        customerDongtaiService.insertBatch(params);
        mapper.updateStatusCancelLock(businessSetBo);
    }


    /**
     * 查询已经锁客多少人
     */
    @Override
    public Integer findLocks(Customer customer){
        return mapper.findLocks(customer);
    }


    /**
     * 锁客
     */
    @Override
    @Transactional(readOnly = false)
    public Integer lockCustomer(Customer customer){
        return mapper.lockCustomer(customer);
    }

    @Override
    public List<Customer> selectToHongHai48(BusinessSetBo businessSetBo) {
        return mapper.selectToHongHai48(businessSetBo);
    }

    @Override
    public List<Customer> selectToHongHai3(BusinessSetBo businessSetBo) {
        return mapper.selectToHongHai3(businessSetBo);
    }

    @Override
    public List<Customer> selectToHongHai15(BusinessSetBo businessSetBo) {
        return mapper.selectToHongHai15(businessSetBo);
    }

    @Override
    public List<Customer> selectIsRepToTime(BusinessSetBo businessSetBo) {
        return mapper.selectIsRepToTime(businessSetBo);
    }

    @Override
    public List<Customer> selectIsLockToTime(BusinessSetBo businessSetBo) {
        return mapper.selectIsLockToTime(businessSetBo);
    }

    @Override
    public List<Customer> selectCustomerIdByJinJianStatus(JinjianInfo jinjianInfo) {
        return mapper.selectCustomerIdByJinJianStatus(jinjianInfo);
    }

    @Override
    public Customer findNotGen(BusinessSetBo businessSetBo) {
        return mapper.findNotGen(businessSetBo);
    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateNotGen(Customer customer) {
        return mapper.updateNotGen(customer);
    }

    @Override
    public int deleteUsersToGongHai(String[] ids) {
        return mapper.deleteUsersToGongHai(ids);
    }

    @Override
    @Transactional(readOnly = false)
    public int insertRongXinKe(String orderNo) {
        String get_url = RongXiangKeAESUtil.HOST+"/crm-report/api/clue/readOrders";
        JSONObject params = new JSONObject();
        params.put("requestId", UUID.randomUUID());
        params.put("voucherCode", RongXiangKeAESUtil.VOUCHER_CODE);
        JSONObject dataJson = new JSONObject();
        dataJson.put("orderNo", orderNo);
        params.put("data",RongXiangKeAESUtil.encrypt(dataJson.toJSONString(),RongXiangKeAESUtil.KEY));
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.doPost(get_url, params));
        if (jsonObject.getInteger("code")!=200) {
            return 0;
        }else{
        String data = RongXiangKeAESUtil.decrypt(jsonObject.getString("data"), RongXiangKeAESUtil.KEY);
        JSONArray customerJsonList = JSONObject.parseArray(data);
        for (int i = 0; i < customerJsonList.size(); i++) {
            JSONObject customerJson = customerJsonList.getJSONObject(i);
            if (null != customerJson) {
                Customer customer = new Customer();
                customer.setLaiyuan("融享客");
                customer.setClueId(customerJson.getString("orderNo"));
                customer.setCusCanal(customerJson.getString("source"));
                customer.setCusBody(customerJson.getString("cstSource"));
                customer.setCusName(customerJson.getString("name"));
                customer.setAge(customerJson.getInteger("age"));
                customer.setRemark(customerJson.getString("productName"));
                customer.setPhone(customerJson.getString("phone"));
                customer.setSex(customerJson.getInteger("sex") == 0 ? "女" : "男");
                customer.setCityName(customerJson.getString("city"));
                Optional.ofNullable(customerJson.getInteger("profession")).ifPresent(v -> {
                    switch (customerJson.getInteger("profession")) {
                        case 200:
                            customer.setWorks("上班族");
                            break;
                        case 300:
                            customer.setWorks("自由职业");
                            break;
                        case 400:
                            customer.setWorks("企业主");
                            break;
                        case 500:
                            customer.setWorks("个体户");
                            break;
                        case 800:
                            customer.setWorks("公务员");
                            break;
                        case 900:
                            customer.setWorks("其他");
                            break;
                    }

                });

                Optional.ofNullable(customerJson.getInteger("incomeMonth")).ifPresent(v -> {
                    customer.setIncomeMonth(customerJson.getInteger("incomeMonth") + "");
                });


                Optional.ofNullable(customerJson.getInteger("loanUse")).ifPresent(v -> {
                    switch (customerJson.getInteger("sesameScore")) {
                        case 0:
                            customer.setSesameScore("无芝麻分");
                            break;
                        case 10:
                            customer.setSesameScore("600分以下");
                            break;
                        case 20:
                            customer.setSesameScore("600~650分");
                            break;
                        case 30:
                            customer.setSesameScore("650~700分");
                            break;
                        case 40:
                            customer.setSesameScore("700分以上");
                            break;
                    }

                });
                Optional.ofNullable(customerJson.getString("loanMoney")).ifPresent(v -> {
                    customer.setAmount(customerJson.getString("loanMoney").substring(0, customerJson.getString("loanMoney").indexOf(".")) + "万元");
                });

                Optional.ofNullable(customerJson.getInteger("loanExpiresMonth")).ifPresent(v -> {
                    customer.setLoanExpiresMonth(customerJson.getInteger("loanExpiresMonth"));
                });

                Optional.ofNullable(customerJson.getInteger("loanUse")).ifPresent(v -> {
                    // 有值的处理逻辑
                    switch (customerJson.getInteger("loanUse")) {

                        case 10:
                            customer.setLoanUse("消费贷");
                            break;
                        case 20:
                            customer.setLoanUse("结婚贷");
                            break;
                        case 30:
                            customer.setLoanUse("购房贷");
                            break;
                        case 40:
                            customer.setLoanUse("装修贷");
                            break;
                        case 50:
                            customer.setLoanUse("购车贷");
                            break;
                        case 60:
                            customer.setLoanUse("教育贷");
                            break;
                        case 70:
                            customer.setLoanUse("旅游贷");
                            break;
                        case 80:
                            customer.setLoanUse("医疗贷");
                            break;
                        case 90:
                            customer.setLoanUse("其他贷");
                            break;
                    }
                });

                Optional.ofNullable(customerJson.getInteger("gjjScop")).ifPresent(v -> {

                    switch (customerJson.getInteger("gjjScop")) {
                        case 0:
                            customer.setAccumulation("无公积金");
                            break;
                        case 10:
                            customer.setAccumulation("缴纳未满6个月");
                            break;
                        case 20:
                            customer.setAccumulation("缴纳6个月以上");
                            break;
                    }
                });


                Optional.ofNullable(customerJson.getInteger("sbScop")).ifPresent(v -> {

                    switch (customerJson.getInteger("sbScop")) {
                        case 0:
                            customer.setSocial("无社保");
                            break;
                        case 10:
                            customer.setSocial("缴纳未满6个月");
                            break;
                        case 20:
                            customer.setSocial("缴纳6个月以上");
                            break;
                    }
                });

                Optional.ofNullable(customerJson.getInteger("house")).ifPresent(v -> {
                    switch (customerJson.getInteger("house")) {
                        case 0:
                            customer.setHouseType("无房产");
                            break;
                        case 10:
                            customer.setHouseType("有房产，不抵押");
                            break;
                        case 20:
                            customer.setHouseType("有房产，可抵押");
                            break;
                    }

                });

                Optional.ofNullable(customerJson.getInteger("car")).ifPresent(v -> {
                    switch (customerJson.getInteger("car")) {
                        case 0:
                            customer.setCarStatus("无车产");
                            break;
                        case 10:
                            customer.setCarStatus("有车产，不抵押");
                            break;
                        case 20:
                            customer.setCarStatus("有车产，可抵押");
                            break;
                    }

                });

                Optional.ofNullable(customerJson.getInteger("baodanScop")).ifPresent(v -> {

                    switch (customerJson.getInteger("baodanScop")) {
                        case 0:
                            customer.setBaodanScop("无保险保单");
                            break;
                        case 10:
                            customer.setBaodanScop("缴纳未满1年");
                            break;
                        case 20:
                            customer.setBaodanScop("缴纳1年以上");
                            break;
                    }
                });
                Optional.ofNullable(customerJson.getInteger("credit")).ifPresent(v -> {

                    switch (customerJson.getInteger("credit")) {
                        case 0:
                            customer.setZx("无信用记录");
                            break;
                        case 10:
                            customer.setZx("信用良好无逾期");
                            break;
                        case 20:
                            customer.setZx("2年内逾期少于9次无90天以上逾期");
                            break;
                        case 30:
                            customer.setZx("2年内逾期少于9次有90天以上逾期");
                            break;
                        case 40:
                            customer.setZx("2年内逾期大于9次");
                            break;
                        case 50:
                            customer.setZx("半年内有60天以上逾期");
                            break;
                        case 60:
                            customer.setZx("半年内无60天以上逾期");
                            break;
                    }
                });
                Optional.ofNullable(customerJson.getInteger("isLoans")).ifPresent(v -> {
                    switch (customerJson.getInteger("isLoans")) {
                        case 0:
                            customer.setIsLoans("无微粒贷");
                            break;
                        case 10:
                            customer.setIsLoans("1~2千");
                            break;
                        case 20:
                            customer.setIsLoans("2~5千");
                            break;
                        case 30:
                            customer.setIsLoans("5千~1万");
                            break;
                        case 40:
                            customer.setIsLoans("1万以上");
                            break;
                    }
                });
                Optional.ofNullable(customerJson.getInteger("manageYears")).ifPresent(v -> {
                    switch (customerJson.getInteger("manageYears")) {

                        case 10:
                            customer.setManageYears("1年以下");
                            break;
                        case 20:
                            customer.setManageYears("1年至5年");
                            break;
                        case 30:
                            customer.setManageYears("5年以上");
                            break;

                    }
                });
                Optional.ofNullable(customerJson.getString("turnover")).ifPresent(v -> {
                    customer.setTurnover(customerJson.getString("turnover"));
                });
                Optional.ofNullable(customerJson.getString("turnoverPublic")).ifPresent(v -> {
                    customer.setTurnoverPublic(customerJson.getString("turnoverPublic"));
                });
                Optional.ofNullable(customerJson.getInteger("workingYears")).ifPresent(v -> {
                    switch (customerJson.getInteger("workingYears")) {
                        case 10:
                            customer.setWorkingYears("0~6个月");
                            break;
                        case 20:
                            customer.setWorkingYears("6~12个月");
                            break;
                        case 30:
                            customer.setWorkingYears("12个月以上");
                            break;
                    }
                });
                Optional.ofNullable(customerJson.getInteger("registAddress")).ifPresent(v -> {
                    customer.setRegistAddress(customerJson.getInteger("registAddress") == 10 ? "本地" : "外地");
                });
                Optional.ofNullable(customerJson.getInteger("hasBusinessLicense")).ifPresent(v -> {
                    switch (customerJson.getInteger("hasBusinessLicense")) {
                        case 0:
                            customer.setHasBusinessLicense("未注册");
                            break;
                        case 10:
                            customer.setHasBusinessLicense("注册1年以下");
                            break;
                        case 20:
                            customer.setHasBusinessLicense("注册1至5年");
                            break;
                        case 30:
                            customer.setHasBusinessLicense("注册5年以上");
                            break;
                    }
                });

                Optional.ofNullable(customerJson.getInteger("creditCard")).ifPresent(v -> {
                    customer.setCreditCard(customerJson.getInteger("creditCard") == 0 ? "无信用卡" : "有信用卡");
                });
                Optional.ofNullable(customerJson.getString("apiSourceName")).ifPresent(v -> {
                    customer.setApiSourceName(customerJson.getString("apiSourceName"));
                });
                Optional.ofNullable(customerJson.getString("followUserName")).ifPresent(v -> {
                    customer.setFollowUserName(customerJson.getString("followUserName"));
                });
                Optional.ofNullable(customerJson.getString("brand")).ifPresent(v -> {
                    customer.setBrand(customerJson.getString("brand"));
                });
                customer.setClueId(orderNo);
                Map map = savePushCustomer(customer);
                if (map.get("code").equals("200")) {
                    String return_url = RongXiangKeAESUtil.HOST + "/crm-report/api/clue/readCallback";
                    params = new JSONObject();
                    params.put("voucherCode", RongXiangKeAESUtil.VOUCHER_CODE);
                    JSONObject data_return=new JSONObject();
                    List<String> orderNoList = new ArrayList<>();
                    orderNoList.add(orderNo);
                    data_return.put("orderNos", orderNoList);
                    data_return.put("status", 1);
                    params.put("data", RongXiangKeAESUtil.encrypt(data_return.toJSONString(),RongXiangKeAESUtil.KEY));
                    params.put("requestId", UUID.randomUUID());
                    JSONObject returnJson = JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                    System.out.println(returnJson);
                }
            }
        }
            return 1;
        }

    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateIsHeart(Customer customer) {
        return mapper.updateIsHeart(customer);
    }

    public static void main(String[] args) {
        String get_url = RongXiangKeAESUtil.HOST+"/crm-report/api/clue/readOrders";
        JSONObject params = new JSONObject();
        params.put("requestId", UUID.randomUUID());
        params.put("voucherCode", RongXiangKeAESUtil.VOUCHER_CODE);
        JSONObject dataJson = new JSONObject();
        dataJson.put("orderNo", "1296492598289448960");
        params.put("data",RongXiangKeAESUtil.encrypt(dataJson.toJSONString(),RongXiangKeAESUtil.KEY));
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.doPost(get_url, params));
        if (jsonObject.getInteger("code")!=200) {

        }else {
            String data = RongXiangKeAESUtil.decrypt(jsonObject.getString("data"), RongXiangKeAESUtil.KEY);
            JSONArray customerJsonList = JSONObject.parseArray(data);
        }
    }
}
